<template>
  <CustomDialog :drag-dialog="dialogInfo" style="z-index:1201;">
    <el-form ref="form" :model="form" :rules="rules" :disabled="!form.busPageInfo.editable" size="mini" label-width="160px">
      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="组织机构" prop="busMainData.sysOrgCode">
            <OrgsetTreeSelect v-model="form.busMainData.sysOrgCode" :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'" :has-priv="true" style="width: 200px" />
          </el-form-item>
          <el-form-item label="业务时间" prop="busMainData.busDate">
            <el-date-picker
              v-model="form.busMainData.busDate"
              placeholder="业务时间"
              type="datetime"
              size="mini"
              clearable
              style="width: 200px"
              class="filter-item" />
          </el-form-item>
          <el-form-item label="开票人" prop="busMainData.invoiceByName">
            <el-input v-model="form.busMainData.invoiceByName" />
          </el-form-item>
          <el-form-item label="收款人" prop="busMainData.cashByName">
            <el-input v-model="form.busMainData.cashByName" />
          </el-form-item>
          <el-form-item label="发票号" prop="busMainData.invoiceNo">
            <el-input v-model="form.busMainData.invoiceNo" />
          </el-form-item>
          <el-form-item label="备注" prop="busMainData.busRmk">
            <el-input
              v-model="form.busMainData.busRmk"
              size="mini"
              class="filter-item" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户" prop="busMainData.otherSysOwnerCpy">
            <CpyOrgSetSelectDialog
              v-model="form.busMainData.busOtherCpyName"
              :editable="form.busPageInfo.editable && form.busMainData.funProcess === '10'"
              :cpy-code="form.busMainData.otherSysOwnerCpy"
              :ori-org-code="form.busMainData.otherSysOrgCode"
              cpy-owner-type="custom"
              @cpySelectCallback="cpySelectCallback"
              @orgSetSelectCallback="orgSetSelectCallback" />
          </el-form-item>
          <el-form-item label="发票类型" prop="busMainData.invoiceType">
            <el-select v-model="form.busMainData.invoiceType" :style="style" size="mini" filterable placeholder="发票类型">
              <el-option
                v-for="(item) in dicts.bus_invoice_type"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"/>
            </el-select>
          </el-form-item>
          <el-form-item label="购方识别号" prop="busMainData.customCerCode">
            <el-input v-model="form.busMainData.customCerCode" />
          </el-form-item>
          <el-form-item label="购方名称" prop="busMainData.customName">
            <el-input v-model="form.busMainData.customName" />
          </el-form-item>
          <el-form-item label="购方地址" prop="busMainData.customAddress">
            <el-input v-model="form.busMainData.customAddress" />
          </el-form-item>
          <el-form-item label="购方银行帐号" prop="busMainData.customBankNo">
            <el-input v-model="form.busMainData.customBankNo" />
          </el-form-item>
          <el-form-item label="购方开户银行名称" prop="busMainData.customBankName">
            <el-input v-model="form.busMainData.customBankName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="类别" prop="busMainData.billType">
            <el-select v-model="form.busMainData.billType" :style="style" size="mini" filterable placeholder="类别">
              <el-option
                v-for="(item) in dicts.invoice_bill_type"
                :key="item.id"
                :label="item.dictName"
                :value="item.dictCode"/>
            </el-select>
          </el-form-item>
          <el-form-item label="销方单位识别号" prop="busMainData.saleCerCode">
            <el-input v-model="form.busMainData.saleCerCode" />
          </el-form-item>
          <el-form-item label="销方名称" prop="busMainData.saleName">
            <el-input v-model="form.busMainData.saleName" />
          </el-form-item>
          <el-form-item label="销方地址" prop="busMainData.saleAddress">
            <el-input v-model="form.busMainData.saleAddress" />
          </el-form-item>
          <el-form-item label="销方银行帐号：" prop="busMainData.saleBankNo">
            <el-input v-model="form.busMainData.saleBankNo" />
          </el-form-item>
          <el-form-item label="销方开户银行名称" prop="busMainData.saleBankName">
            <el-input v-model="form.busMainData.saleBankName" />
          </el-form-item>
          <el-form-item label="附档" prop="attachmentList">
            <FileUpload
              ref="fileUpload"
              :editable="form.busPageInfo.editable"
              :sup_this="sup_this"
              :file-limit="5"
              :is-direct-upload="true"
              list-type="list"
              @fileRemoveSuccess="fileRemoveSuccess"
              @fileUploadSuccess="fileUploadSuccess"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-collapse v-model="activeNames">
      <el-collapse-item title="发票明细" name="1">
        <invoice-detail ref="invoiceDetail" :bus-main-data="form.busMainData" :invoice-details="form.invoiceDetails" :editable="form.busPageInfo.editable" @setDetails="setDetails" />
      </el-collapse-item>
    </el-collapse>
    <div v-if="form.busPageInfo.editable" slot="footer" class="modal-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','FIN_INVOICE_ALL','FIN_INVOICE_CHANGE','FIN_INVOICE_CREATE']" :loading="loading" type="primary" @click="doSave">暂存</el-button>
      <el-button v-permission="['SYS_ADMIN','COMMON_ADMIN','FIN_INVOICE_ALL','FIN_INVOICE_SUBMIT']" :loading="loading" type="primary" @click="doSubmit">提交</el-button>
    </div>
  </CustomDialog>
</template>

<script>
import finInvoice from '@/api/fin/FinInvoice'
import InvoiceDetail from './invoiceDetail'
import CpyOrgSetSelectDialog from '@/views/components/CpyOrgSetSelectDialog'
import OrgsetTreeSelect from '@/views/components/OrgsetTreeSelect'

export default {
  components: { InvoiceDetail, CpyOrgSetSelectDialog, OrgsetTreeSelect },
  dictTypes: ['invoice_bill_type', 'bus_invoice_type'],
  props: {
    sup_this: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isAdd: false,
      isRedirect: false,
      loading: false,
      style: 'width: 184px',
      activeNames: ['1'],
      dialogInfo: {
        name: 'finInvoiceMngFormDialog',
        title: '发票管理',
        fullScreen: true,
        width: 500,
        height: 90
      },
      form: {
        invoiceDetails: [],
        busMainData: {
          id: '',
          enableFlag: 'Y'
        },
        busPageInfo: {
          editable: false
        }
      },
      rules: {
        'busMainData.busDate': [
          { required: true, message: '请选择业务时间', trigger: 'blur' }
        ],
        'busMainData.invoiceType': [
          { required: true, message: '请选择发票类型', trigger: 'blur' }
        ],
        'busMainData.sysOrgCode': [
          { required: true, message: '请选择机构', trigger: 'blur' }
        ],
        'busMainData.otherSysOwnerCpy': [
          { required: true, message: '请选择客户', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    fileRemoveSuccess(file) {
      this.form.attachmentList = this.form.attachmentList.filter(t => t.filePath !== file.filePath)
    },
    fileUploadSuccess(sysAttachment) {
      this.form.attachmentList.push(sysAttachment)
    },
    cancel() {
      this.resetForm()
    },
    initDataOfBefore() {
    },
    displayDialog() {
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.show(name)
      })
    },
    hiddenDialog() {
      this.isRedirect = false
      const { name } = this.dialogInfo
      this.$nextTick(() => {
        this.$modal.hide(name)
      })
    },
    getOtherDetailData(mainId, replaceFlag, replaceDetailLotFlag) {
      if (mainId) {
        finInvoice.getDetailData(mainId, replaceFlag, replaceDetailLotFlag).then(res => {
          this.form.invoiceDetails = res.data
        })
      }
      setTimeout(() => {
        this.$refs.fileUpload.setFileList(this.form.attachmentList)
      }, 200)
    },
    addData() {
      this.isAdd = true
      const data = { paramBean: {}}
      finInvoice.toAdd(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(null, true, true)
      }).catch(err => {
        console.log(err)
      })
    },
    copyData(mainId) {
      this.isAdd = true
      const data = { paramBean: { id: mainId }}
      finInvoice.toCopy(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(mainId, true, true)
      }).catch(err => {
        console.log(err)
      })
    },
    viewMainData(id) {
      this.isAdd = false
      const data = { paramBean: { id: id }}
      finInvoice.viewMainData(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(id, false, false)
      })
    },
    doSubmit() {
      this.doSingleSave(true)
    },
    doSave() {
      this.doSingleSave(false)
    },
    doSingleSave(isSubmit) {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.formSubmit = isSubmit
          this.loading = true
          if (this.isAdd) {
            this.doAdd()
          } else {
            this.doEdit()
          }
        }
      })
    },
    doAdd() {
      finInvoice.addOrEdit(this.form).then(res => {
        this.loading = false
        if (this.isRedirect) {
          this.$router.push({ path: '/fin/fininvoice' })
        } else {
          this.sup_this.init()
        }
        this.resetForm()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      finInvoice.addOrEdit(this.form).then(res => {
        this.resetForm()
        this.loading = false
        this.sup_this.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.hiddenDialog()
      this.$refs['form'].resetFields()
    },
    changeData(busId) {
      const data = { paramBean: { id: busId }}
      finInvoice.toChange(data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(this.form.busMainData.oldMainId, true, false)
      }).catch(err => {
        console.log(err)
      })
    },
    cpySelectCallback(selectedRow, selectObj) {
      this.form.busMainData.otherSysOwnerCpy = ''
      this.form.busMainData.busOtherCpyName = ''
      if (selectedRow) {
        this.form.busMainData.otherSysOwnerCpy = selectedRow.cpyCode
        this.form.busMainData.busOtherCpyName = selectedRow.cpyLongName
        // 客户的收货信息
        this.form.orderExt.customCerCode = selectedRow.cerCode
        this.form.orderExt.customName = selectedRow.cpyLongName
        this.form.orderExt.customAddress = selectedRow.officeAddress
        this.form.orderExt.customBankNo = selectedRow.bankAccount
        this.form.orderExt.customBankName = selectedRow.bankName
      }
      selectObj.cancel()
    },
    orgSetSelectCallback(orgCode) {
      this.form.busMainData.otherSysOrgCode = orgCode
    },
    setDetails(details) {
      this.form.invoiceDetails = details
    },
    addDataFromWaitOrder(busRelList) {
      this.isAdd = true
      this.isRedirect = true
      const data = { busRelList: busRelList, paramBean: {}}
      finInvoice.postRequestByName('toAddFromWaitOrder', data).then(res => {
        this.displayDialog()
        this.form = res.data
        this.getOtherDetailData(null, true, true)
      }).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
